package com.xnyzc.lhy.didi.service.impl.checkstand;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.xnyzc.lhy.common.component.didi.DiDiUrlConstant;
import com.xnyzc.lhy.common.component.redis.RedisCommon;
import com.xnyzc.lhy.common.constant.RedisPrefixConstant;
import com.xnyzc.lhy.common.entity.DiDiRv;
import com.xnyzc.lhy.common.entity.ParameterEnum;
import com.xnyzc.lhy.common.entity.Qw;
import com.xnyzc.lhy.common.exception.DiDiException;
import com.xnyzc.lhy.common.penum.EDiDiErrorCode;
import com.xnyzc.lhy.common.penum.order.EDiDiOrderStatus;
import com.xnyzc.lhy.common.penum.order.EOrderStatus;
import com.xnyzc.lhy.common.penum.pay.EPayType;
import com.xnyzc.lhy.common.util.CheckUtil;
import com.xnyzc.lhy.common.util.RequestMethodUtil;
import com.xnyzc.lhy.common.util.sign.AttestationTool;
import com.xnyzc.lhy.didi.entity.order.OaCOrderPersonal;
import com.xnyzc.lhy.didi.entity.param.checkstand.PaymentNoticeParam;
import com.xnyzc.lhy.didi.entity.param.operation.CloseOrderParam;
import com.xnyzc.lhy.didi.entity.param.pay.PayDetails;
import com.xnyzc.lhy.didi.entity.param.pay.PayInfo;
import com.xnyzc.lhy.didi.entity.param.pay.PayTrade;
import com.xnyzc.lhy.didi.entity.param.pay.Payment;
import com.xnyzc.lhy.didi.mapper.order.OaCOrderPersonalMapper;
import com.xnyzc.lhy.didi.mapper.order.OaDOrderMapper;
import com.xnyzc.lhy.didi.service.checkstand.CheckstandService;
import com.xnyzc.lhy.order.entity.order.OaDOrder;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * <p>
 * 收银台相关
 * </p>
 *
 * @author wangshuo
 * @since 2019-10-07
 */
@Service
public class CheckstandServiceImpl implements CheckstandService {

    @Autowired
    private RedisCommon redisCommon;

    @Autowired
    private OaCOrderPersonalMapper oaCOrderPersonalMapper;

    @Autowired
    private OaDOrderMapper oaDOrderMapper;

    /**
     * 支付详情查询
     *
     * @param param 入参实体
     * @return
     */
    @Override
    public PayInfo getPayInfo(CloseOrderParam param) {
        if (StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getOpen_oid())) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        String url = DiDiUrlConstant.didiUrl + DiDiUrlConstant.GET_PAY_INFO_API;
        param.setApp_id(DiDiUrlConstant.didiAppId);
        param.setSign(DiDiUrlConstant.didiSignPro);
        Date date = new Date();
        String timestamp = String.valueOf(date.getTime() / 1000);
        param.setTimestamp(timestamp);
        String signParameter = AttestationTool.getSign(param, DiDiUrlConstant.X_WWW_FORM_URLENCODED);
        String data = RequestMethodUtil.requestMethod(signParameter, url);
        if (CheckUtil.strIsEmpty(data)) {
            throw DiDiException.create(EDiDiErrorCode.httpRequestDidiUrlError);
        }
        JSONObject jsonObject = JSONObject.parseObject(data);
        if (jsonObject.get(DiDiUrlConstant.ERRNO).equals(EDiDiErrorCode.success.getValue())) {
            // 成功
            PayInfo payInfo;
            try {
                payInfo = JSONObject.parseObject(jsonObject.getString("data"), PayInfo.class);
            } catch (Exception e) {
                throw DiDiException.create(EDiDiErrorCode.jsonConvertError);
            }
            return payInfo;
        } else {
            DiDiRv diDiRv;
            try {
                diDiRv = JSONObject.parseObject(data, DiDiRv.class);
            } catch (Exception e) {
                throw DiDiException.create(EDiDiErrorCode.jsonConvertError);
            }
            return null;
        }
    }

    /**
     * 支付通知
     *
     * @return
     */
    @Override
    public DiDiRv getPaymentNotice(PaymentNoticeParam param) {
        if (StringUtils.isBlank(param.getOpen_oid()) || StringUtils.isBlank(param.getOrder_id()) || StringUtils.isBlank(param.getType())) {
            return DiDiRv.wrapError(EDiDiErrorCode.parameterError);
        }
        //首先从redis中获取订单,如果redis中为获取到订单查询数据库
        OaCOrderPersonal oaCOrderPersonal = null;
        String orderNo = param.getOrder_id();
        String str = redisCommon.getStr(RedisPrefixConstant.ORDER_OA_D_ORDER + orderNo);
        if (CheckUtil.strIsNotEmpty(str)) {
            oaCOrderPersonal = JSON.parseObject(str, OaCOrderPersonal.class);
        } else {
            List<OaCOrderPersonal> oaCOrderPersonals = oaCOrderPersonalMapper.selectList(Qw.create().eq(OaCOrderPersonal.ORDER_NO, orderNo));
            if (oaCOrderPersonals.size() > 0) {
                oaCOrderPersonal = oaCOrderPersonals.get(0);
            }
        }
        //判断是否获取到了当前订单
        if (CheckUtil.objIsEmpty(oaCOrderPersonal)) {
            throw DiDiException.create(EDiDiErrorCode.parameterError);
        }
        // == 0 支付通知 == 1 预支付通知
        if (param.getType().equals(ParameterEnum.ZERO.getTypeName())) {
            // 查询支付详情设置用户支付金额
            CloseOrderParam closeOrderParam = new CloseOrderParam();
            closeOrderParam.setOrder_id(orderNo);
            closeOrderParam.setOpen_oid(param.getOpen_oid());
            PayInfo payInfo = getPayInfo(closeOrderParam);
            List<PayTrade> payTradeList = payInfo.getPay_trade_list();
            List<Payment> payments = payInfo.getPayments();
            Integer actualFee = 0;
            if (CheckUtil.collectionIsEmpty(payTradeList)) {
                throw DiDiException.create(EDiDiErrorCode.didiRequestPaymentNoticeNotInfo);
            }
            for (PayTrade payTrade: payTradeList) {
                actualFee += payTrade.getCost();
            }
            PayTrade payTrade = payTradeList.get(0);
            String tradeNo = payTrade.getTrade_no();
            BigDecimal bigDecimal = new BigDecimal(actualFee.toString());
            bigDecimal = bigDecimal.divide(new BigDecimal("100"));
            // 更改司机接单表状态
            UpdateWrapper<OaDOrder> dOrderUpdate = new UpdateWrapper<>();
            dOrderUpdate.set(OaDOrder.ORDER_STATUS, EOrderStatus.paymented.getType());
            dOrderUpdate.eq(OaDOrder.ORDER_NO, orderNo);
            try {
                oaDOrderMapper.update(null, dOrderUpdate);
            }catch (Exception e) {
                throw DiDiException.create(e.getMessage());
            }
            UpdateWrapper<OaCOrderPersonal> updateWrapper = new UpdateWrapper<>();
            if (CheckUtil.collectionIsNotEmpty(payments)) {
                Payment payment = payments.get(0);
                List<PayDetails> pay_details = payment.getPay_details();
                if (CheckUtil.collectionIsNotEmpty(pay_details)) {
                    for (PayDetails payDetails: pay_details) {
                        if (CheckUtil.strIsNotEmpty(payDetails.getChannel_name()) && payDetails.getChannel_name().contains("优惠券")) {
                            updateWrapper.set(OaCOrderPersonal.COUPON_ID, payDetails.getCoupon_id());
                            updateWrapper.set(OaCOrderPersonal.COUPON_DEDUCTION_FEE, payDetails.getCost());
                        }
                    }
                }
            }
            updateWrapper.set(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion() + 1);
            updateWrapper.set(OaCOrderPersonal.ORDER_STATUS, EOrderStatus.paymented.getType());
            updateWrapper.set(OaCOrderPersonal.DIDI_ORDER_STATUS, EDiDiOrderStatus.paymented.getDidiType());
            updateWrapper.set(OaCOrderPersonal.ACTUAL_FEE, bigDecimal);
            if (payTrade.getChannel().contains(EPayType.alipay.getValue())) {
                updateWrapper.set(OaCOrderPersonal.PAYMENT_TYPE, EPayType.alipay.getType());
            } else if (payTrade.getChannel().contains(EPayType.weChat.getValue())) {
                updateWrapper.set(OaCOrderPersonal.PAYMENT_TYPE, EPayType.weChat.getType());
            } else {
                updateWrapper.set(OaCOrderPersonal.PAYMENT_TYPE, EPayType.balance.getType());
            }
            updateWrapper.set(OaCOrderPersonal.PASSENGER_PAY_TIME, new Date());
            updateWrapper.set(OaCOrderPersonal.EXPAND1, tradeNo);
            updateWrapper.eq(OaCOrderPersonal.ORDER_NO, orderNo);
            updateWrapper.eq(OaCOrderPersonal.VERSION, oaCOrderPersonal.getVersion());
            return DiDiRv.wrapSuccess(oaCOrderPersonalMapper.update(null, updateWrapper) > 0 ? EDiDiErrorCode.success : EDiDiErrorCode.updateOrderInfoFail);
        }
        return DiDiRv.wrapSuccess(EDiDiErrorCode.success);
    }


}
